<template>
  <div class="app-layout">
    <header class="app-header">
      <div class="header-content">
        <div class="logo">
          <router-link to="/" class="logo-link">
            <span class="logo-icon">🤖</span>
            <span class="logo-text">AI角色扮演</span>
          </router-link>
        </div>
        
        <nav class="main-nav">
          <router-link to="/role-square" class="nav-item">角色广场</router-link>
          <router-link to="/my-roles" class="nav-item">我的角色</router-link>
          <router-link to="/chat" class="nav-item">会话记录</router-link>
        </nav>
        
        <div class="user-section">
          <div v-if="user" class="user-info">
            <span class="username">{{ user.username }}</span>
            <div class="user-menu">
              <button class="user-avatar" @click="toggleUserMenu">
                <img v-if="user.avatarUrl" :src="user.avatarUrl" :alt="user.username" />
                <span v-else class="avatar-placeholder">{{ user.username.charAt(0).toUpperCase() }}</span>
              </button>
              <div v-if="showUserMenu" class="user-dropdown">
                <router-link to="/profile" class="dropdown-item">个人中心</router-link>
                <router-link to="/settings" class="dropdown-item">设置</router-link>
                <hr class="dropdown-divider" />
                <button @click="logout" class="dropdown-item logout">退出登录</button>
              </div>
            </div>
          </div>
          <router-link v-else to="/login" class="login-btn">登录</router-link>
        </div>
      </div>
    </header>
    
    <main class="app-main">
      <slot />
    </main>
    
    <footer class="app-footer">
      <div class="footer-content">
        <p>&copy; 2024 AI角色扮演平台. 让AI成为你的专属伙伴.</p>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const user = ref(null)
const showUserMenu = ref(false)

const loadUser = async () => {
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      user.value = null
      return
    }
    
    // 验证token是否有效，获取最新用户信息
    const res = await fetch('/api/users/profile', {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    if (res.ok) {
      const data = await res.json()
      if (data.code === 0) {
        user.value = data.data
        localStorage.setItem('auth_user', JSON.stringify(data.data))
      } else {
        // token无效，清除本地存储
        localStorage.removeItem('auth_token')
        localStorage.removeItem('auth_user')
        user.value = null
      }
    } else {
      // 请求失败，清除本地存储
      localStorage.removeItem('auth_token')
      localStorage.removeItem('auth_user')
      user.value = null
    }
  } catch (e) {
    console.error('加载用户信息失败', e)
    localStorage.removeItem('auth_token')
    localStorage.removeItem('auth_user')
    user.value = null
  }
}

const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value
}

const logout = () => {
  localStorage.removeItem('auth_token')
  localStorage.removeItem('auth_user')
  user.value = null
  showUserMenu.value = false
  window.dispatchEvent(new CustomEvent('user-logout'))
  router.push('/login')
}

const closeUserMenu = (e) => {
  if (!e.target.closest('.user-menu')) {
    showUserMenu.value = false
  }
}

onMounted(() => {
  loadUser()
  document.addEventListener('click', closeUserMenu)
  
  // 监听登录状态变化事件
  window.addEventListener('user-login', loadUser)
  window.addEventListener('user-logout', () => {
    user.value = null
  })
})

onUnmounted(() => {
  document.removeEventListener('click', closeUserMenu)
  window.removeEventListener('user-login', loadUser)
  window.removeEventListener('user-logout', () => {
    user.value = null
  })
})
</script>

<style scoped>
.app-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.app-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  width: 100%;
  padding: 0 32px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 72px;
}

.logo-link {
  display: flex;
  align-items: center;
  gap: 8px;
  text-decoration: none;
  color: white;
  font-weight: 600;
  font-size: 20px;
}

.logo-icon {
  font-size: 24px;
}

.main-nav {
  display: flex;
  gap: 40px;
}

.nav-item {
  color: rgba(255,255,255,0.9);
  text-decoration: none;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.2s;
}

.nav-item:hover,
.nav-item.router-link-active {
  color: white;
  background: rgba(255,255,255,0.1);
}

.user-section {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-weight: 500;
}

.user-menu {
  position: relative;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: 2px solid rgba(255,255,255,0.3);
  background: rgba(255,255,255,0.1);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.user-avatar:hover {
  border-color: rgba(255,255,255,0.6);
  background: rgba(255,255,255,0.2);
}

.user-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-placeholder {
  color: white;
  font-weight: 600;
  font-size: 14px;
}

.user-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 8px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
  min-width: 160px;
  overflow: hidden;
}

.dropdown-item {
  display: block;
  padding: 12px 16px;
  color: #374151;
  text-decoration: none;
  font-size: 14px;
  transition: background 0.2s;
  border: none;
  background: none;
  width: 100%;
  text-align: left;
  cursor: pointer;
}

.dropdown-item:hover {
  background: #f3f4f6;
}

.dropdown-item.logout {
  color: #dc2626;
}

.dropdown-divider {
  margin: 0;
  border: none;
  border-top: 1px solid #e5e7eb;
}

.login-btn {
  background: rgba(255,255,255,0.2);
  color: white;
  text-decoration: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.login-btn:hover {
  background: rgba(255,255,255,0.3);
}

.app-main {
  flex: 1;
  background: #f8fafc;
  overflow-y: auto;
  min-height: 0;
}

.app-footer {
  background: #1f2937;
  color: #9ca3af;
  padding: 20px 0;
  text-align: center;
}

.footer-content {
  width: 100%;
  padding: 0 32px;
}

@media (max-width: 768px) {
  .header-content {
    padding: 0 16px;
  }
  
  .main-nav {
    gap: 16px;
  }
  
  .nav-item {
    padding: 6px 12px;
    font-size: 14px;
  }
  
  .username {
    display: none;
  }
}
</style>
